package com.elite.groovy.callback

import com.elite.groovy.kh.KHUtil
import com.elite.groovy.kh.LogToDB
import com.elite.groovy.util.EliteBean
import net.sf.json.JSONArray
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.springframework.jdbc.core.JdbcTemplate

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 * @projectName: ngsapitask-sw
 * @className: apiUnicomSMSResult
 * @author: LiJT
 * @description: 联通短信平台发送成功回调API
 * @date: 2022-09-27 00:12
 * @version: 1.0
 */

public class apiSMSResultReport implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiSMSResultReport.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        long startTime = System.currentTimeMillis();

        // 获取所有Header
        Map<String, String> mapHeader = new HashMap<String, String>();
        Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            String value = request.getHeader(key);
            log.debug("Call Header-" + key + ":" + value);

            mapHeader.put(key, value);
        }

        String inData = "";
        JSONObject outData = new JSONObject();

        String getMethod = request.getMethod();
        log.debug("getMethod:" + getMethod);
        if (getMethod.equals("GET")) {
            inData = request.getParameter("data");
            log.debug("原始Get请求参数:" + inData);
        } else {
            InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
            BufferedReader iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                inData += line;
            }
            log.debug("原始Post请求参数:" + inData);
        }

        try {
            // 获取报告信息
            String sms_StatusJson = URLDecoder.decode(form2Map(URLDecoder.decode(inData, "UTF-8")).get("sms_status").toString(), "UTF-8");

            // 解析短信结果推送
            JSONArray sendResultArr = JSONArray.fromObject(sms_StatusJson);

            // 定义批量更新SQL
            String batchUpdate = '''Update Documentout
                                       Set Report_Status     = ?,
                                           User_Receive_Time = ?,
                                           Modifiedby        = 'SELITE',
                                           Modifieddate      = Now(),
                                           Synchronize_Time  = Now(),
                                           Error_Detail      = ?
                                     Where Uid = ?''';

            String batchInsert = '''Insert Into Dg_Sms_Resreport_Log
                                      (Rec_Guid, Sid, Uid, Mobile, Report_Status, User_Receive_Time, Error_Msg, Error_Detail, Sync_Time)
                                    Values
                                      (Uuid(), ?, ?, ?, ?, ?, ?, ?, Now())''';






            // 解析返回信息
            int loopNum = 0;
            int listSize = sendResultArr.size();
            List<Object[]> paramListIns = new ArrayList<>();
            List<Object[]> paramLogsIns = new ArrayList<>();
            JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());
            for (int i = 0; i < listSize; i++) {

                String sid = KHUtil.GetSFJV(sendResultArr.getJSONObject(i), "sid");
                String uid = KHUtil.GetSFJV(sendResultArr.getJSONObject(i), "uid");
                String mobile = KHUtil.GetSFJV(sendResultArr.getJSONObject(i), "mobile");
                String report_status = KHUtil.GetSFJV(sendResultArr.getJSONObject(i), "report_status");
                String user_receive_time = KHUtil.GetSFJV(sendResultArr.getJSONObject(i), "user_receive_time");
                String error_msg = KHUtil.GetSFJV(sendResultArr.getJSONObject(i), "error_msg");
                String error_detail = KHUtil.GetSFJV(sendResultArr.getJSONObject(i), "error_detail");
                log.debug("短信结果推送处理-sid:" + sid + " uid:" + uid + " report_status:" + report_status + " user_receive_time:" + user_receive_time);

                String[] paramArr = new String[4];
                paramArr[0] = report_status;
                paramArr[1] = user_receive_time;
                paramArr[2] = error_detail;
                paramArr[3] = uid;
                paramListIns.add(paramArr);

                String[] paramLogArr = new String[7];
                paramLogArr[0] = sid;
                paramLogArr[1] = uid;
                paramLogArr[2] = mobile;
                paramLogArr[3] = report_status;
                paramLogArr[4] = user_receive_time;
                paramLogArr[5] = error_msg;
                paramLogArr[6] = error_detail;
                paramLogsIns.add(paramLogArr);

                loopNum++;


                List DocumentoutList = eliteBean.chaxun_sql("select CreatedBy from Documentout from uid="+uid+"","dataSource");


                if(!error_detail.equals("")) {
                    sendMsg_Note(eliteBean, "" + mobile + "短信发送失败", "当前短信发送失败信息(" + error_detail + ")", DocumentoutList.get(0).get("CreatedBy"), "开发", "1");
                }

                // 如果当前批次已经到100提交一次DB
                if (loopNum >= 200) {

                    log.debug("短信结果推送处理-如果当前批次已经到" + loopNum + "提交一次DB");
                    jt.batchUpdate(batchUpdate, paramListIns);
                    jt.batchUpdate(batchInsert, paramLogsIns);
                    log.debug("短信结果推送处理-如果当前批次已经到" + loopNum + "提交一次DB End");
                    paramListIns.clear();

                    loopNum = 0;
                }



            }

            // 最后批次未达到200提交一次DB
            if (loopNum > 0) {
                log.debug("短信结果推送处理-最后批次达到" + loopNum + "提交一次DB");
                jt.batchUpdate(batchUpdate, paramListIns);
                jt.batchUpdate(batchInsert, paramLogsIns);
                log.debug("短信结果推送处理-最后批次达到" + loopNum + "提交一次DB End");
            }

            // 失败返回
            outData.put("code", "0");
            outData.put("msg", "短信结果推送处理-处理完成,总条数:" + listSize);

        } catch (Exception e) {
            log.error("短信结果推送处理-接口处理异常" + e.getMessage(), e);
            // 失败返回
            outData.put("code", "-1");
            outData.put("msg", "短信结果推送处理-接口处理异常");
        } finally {
            LogToDB.toDB(eliteBean, "dataSource", "短信平台发送报告推送[普通]", "apiSMSResultReport", inData, outData.toString(), (System.currentTimeMillis() - startTime).toString(), "/");
        }

        log.debug("短信结果推送处理-处理完成返回结果:" + outData.toString());

        return outData.toString();
    }


    /**
     * 表单字符串转化成 hashMap
     *
     * @param orderinfo
     * @return
     */

    public static HashMap<String, String> form2Map(String orderinfo) {
        String[] listinfo;
        HashMap<String, String> map = new HashMap<String, String>();
        listinfo = orderinfo.split("&");
        for (String s : listinfo) {
            String[] list = s.split("=");
            if (list.length > 1) {
                map.put(list[0], list[1]);
            }
        }
        return map;
    }

    /**
     * 消息便签发送
     *
     * @param Lijt
     * @return
     */

    public static boolean sendMsg_Note(EliteBean eliteBean, String Subject, String Content, String Staffid, String StaffName, String Priority) {

        String note_Guid = KHUtil.getRandomString(36);
        String Msg_Note_Staff = "Insert Into Msg_Note_Staff (Msgid, Staffid, Readtime, Flag, Replied, Deleted) Values ('" + note_Guid + "', '" + Staffid + "', Null, 0, 0, 0)";
        String Msg_Note = "Insert Into Msg_Note (Id, Subject, Priority, Receiver, Createdby, Createdtime, Deleted, Content) Values ('" + note_Guid + "', '" + Subject + "', '" + Priority + "', '" + StaffName + "', 'SELITE', Now(), 0, '" + Content + "</br></br><span style=\"color:red\">⚠本便签由系统自动发出，请勿直接回复！</span>')";
        eliteBean.update(Msg_Note_Staff, "dataSource");
        eliteBean.update(Msg_Note, "dataSource");

    }
}